<template>
    <div>
        <header>
            <el-form  class="searchWrap" :size="customStyle.size" :model="sendData">
                <el-form-item>
                    <el-input v-model="sendData.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-date-picker
                        v-model="sendData.create_time"
                        type="date"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy_MM_dd"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :size="customStyle.size" @click="getTableData()">搜 索</el-button>
                </el-form-item>
            </el-form>
        </header>
        <order-info :platformData="platformData" :orderData="tableData" :tableSlots="tableSlots">
            <template #handle="scope">
                <div class="controlBth" v-if="scope.row.platform">
                    <el-button size="mini" type="primary" plain
                               @click="scope.row.senduser?changeTogether(scope.row,true):copyOrder(scope.row,scope.row.username===userInfo.username || scope.row.operateUser === userInfo.username)">
                        复制
                    </el-button>
                    <el-button size="mini" type="primary" plain
                               @click="getLogs(scope.row.username,scope.row.logs)">
                        查看记录
                    </el-button>
                </div>
            </template>
        </order-info>
        <el-dialog :append-to-body="true"
            :close-on-click-modal="false"
            :title="logsDailog.title"
            :visible.sync="logsDailog.visible"
            width="70%"
        >
            <el-table
                :data="logsDailog.logsData"
                border
                stripe
            >
                <el-table-column
                    prop="create_time"
                    width="100px"
                    label="时间">
                </el-table-column>
                <el-table-column
                    prop="input"
                    min-width="100px"
                    label="创建订单">
                    <template #default="scope">
                        <div class="logInfo" v-html="scope.row.input"></div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="output"
                    min-width="200px"
                    label="生成订单">
                    <template #default="scope">
                        <div class="logInfo" v-html="scope.row.output"></div>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import {getOrder, orderCountDown, setOrder} from '@/api/order'
import moment from 'moment'
import tableMixin from '@/mixins/table'
import {getTag} from "@/api/tag";
import OrderInfo from "@/components/order-info";
import isArray from "lodash/isArray";
import cloneDeep from "lodash/cloneDeep";
import {mapGetters} from 'vuex'
const evil = window.eval;
export default {
    name: "record",
    components:{
        OrderInfo
    },
    mixins:[tableMixin],
    data() {
        return {
            tableSlots:[
                {
                    prop:'handle',
                    label:'操作',
                    minWidth:'60px'
                }
            ],
            logsDailog:{
                logsData:[],
                visible: false,
                title:'',
            },
            platformData:[],
            sendFormData:{
                senduser: '',
                note: '',
                operateUser: '',
                platform: [],
                username: '',
                onlyCode: [],
                onlyName: [],
                code: [],
                name: [],
                price: []
            },
            sendData:{
                username:'',
                create_time:'',
            },
            dialogVisible: false,
        }
    },
    computed:{
        useResult() {
            const platform = this.sendFormData.platform;
            return this.orderTimeMap.map((i,index)=>platform[index]?this.platformData.find(i => i.value === platform[index]):{isReady: 0, type: 0,step:0})
        },
        isShopUse() {
            return (index=0)=>{
                return this.useResult[index].isReady
            }
        },
        isUseName() {
            return (index=0)=>{
                return this.useResult[index].type
            }
        },
        orderParamsMap() {
            return (index=0)=>{
                return ['code', 'price', 'name'].filter(k => this.isUseName(index) ? k !== 'code' : true)
            }
        },
        ...mapGetters([
            'orderTimeMap',
            'orderTimeControl',
            'userOrder'
        ])
    },
    created() {
        this.sendData.create_time =moment().format('YYYY_MM_DD');
        //关闭页面异常订单风控
        getTag({type:0}).then(res=>{
            this.platformData=res.data
        })
    },
    methods: {
        evil,
        async setCountDown(senduser) {
            if(!this.userOrder[senduser]){
                await setTimeout(async () => {
                    await orderCountDown({senduser}).then(res => {
                        const {orderTimeLimit, startTime} = res.data
                        this.$store.commit('system/SET_ORDER_TIME_LIMIT', {orderTimeLimit, startTime})
                        this.$store.commit('exclude/SET_HAD_USER',[senduser,1])
                    })
                }, this.ioAwaitTime)
            }
        },
        changeTogether(item){
            if(!this.userInfo.authBtn.includes('/order/changeTogether')){
                return this.$message.error('订单类型为拼团订单')
            }else {
                this.showConfirm(`确认复制此条拼团订单？`).then(() => {
                    this.copyOrder(item)
                })
            }
        },
        copyOrder(item) {
            //拒绝订单拒绝不验证名字
            item.price=isArray(item.price) && item.price.filter(v=>v!=='0')
            if(isArray(item.code)){
                item.code=item.code.map(v=>{
                    const index=(item.note || []).findIndex(i=>i.includes(v))
                    if(index>-1){
                        v=item.note[index]
                    }
                    return v
                }).filter(v=>v)
            }
            if(isArray(item.name)){
                item.name=item.name.map(v=>{
                    const index=(item.note || []).findIndex(i=>i.includes(v))
                    if(index>-1){
                        v=item.note[index]
                    }
                    return v
                }).filter(v=>v)
            }
            const sendFormData=this.sendFormData
            sendFormData.senduser = cloneDeep(item.senduser)
            sendFormData.platform = cloneDeep(item.platform)
            sendFormData.operateUser = this.userInfo.username
            sendFormData.username = this.userInfo.username
            this.orderTimeMap.map((t, index) => {
                if(this.isShopUse(index)){
                    this.isUseName(index) ? (sendFormData.onlyName = cloneDeep(item.name)) :
                        (sendFormData.onlyCode = cloneDeep(item.code));
                }else {
                    const dataLen=this.isUseName(index)?item.name.length:item.code.length
                    this.orderParamsMap(index).map(k => {
                        this.$set(sendFormData[k],index,cloneDeep(item[k][index] ? item[k][index].split(','):new Array(dataLen).fill('')))
                    })
                }
            })
            this.saveOrder(item.senduser)
        },
        saveOrder(){
            const realSendFormData = {};
            const sendFormData=this.sendFormData
            realSendFormData.note = sendFormData.note
            realSendFormData.name = isArray(sendFormData.name) && sendFormData.name.map(i=>i.join(','));
            realSendFormData.code = isArray(sendFormData.code) && sendFormData.code.map(i=>i.join(','));
            realSendFormData.price = isArray(sendFormData.price) && sendFormData.price.map(i=>i.join(','));
            realSendFormData.platform = sendFormData.platform
            realSendFormData.username = sendFormData.username
            realSendFormData.operateUser = sendFormData.operateUser
            setOrder(realSendFormData).then(async res => {
                this.$message.success(res.msg)
                await this.setCountDown(sendFormData.username)
                const startTime = this.orderTimeControl.startTime
                const seconds = (new Date()).getTime() - startTime
                const durationTime = moment.duration(seconds).seconds()
                //相差秒数
                const remainTime = this.orderTimeControl.orderTimeLimit - durationTime * 1000
                remainTime >= 0 && this.$store.commit('exclude/SET_COUNT_DOWN', remainTime)
            })
        },
        getLogs(username,data){
            console.log(username)
            this.logsDailog.logsData=data
            this.logsDailog.visible=true
            this.logsDailog.title=`${username}点餐记录`
        },
        tableApi:getOrder,
    }
}
</script>

<style scoped lang="scss">

.innerForm {
    .item {
        display: flex;
        border-bottom:1px solid #eee;
        padding:8px 10px;
        span {
            flex:none;
            margin-right:30px;
        }
        &:last-child {
            border:none;
        }
    }
}
>>> .el-table__row {
    .orderItem {
        border-bottom:1px solid #eee;
        padding:8px 10px;
        &:last-child {
            border:none;
        }
    }
}

</style>
